package com.ifcreate.infowell.common.util;


import cn.hutool.core.util.StrUtil;
import com.ifcreate.infowell.common.annotation.CNotBlank;
import com.ifcreate.infowell.common.annotation.CNotNull;
import com.ifcreate.infowell.common.exception.CustomException;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/**
 * @Author chenzedeng
 * @Email yustart@foxmail.com
 * @Create 2020-03-19 3:29 下午
 */
@Aspect
@Component
public class FieldCheckAdvice {


    @Before("execution(public * com.ifcreate.infowell.*.controller..*.*(..)))")
    public void beforeNotBlank(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            Annotation[] annotations = parameters[i].getDeclaredAnnotations();
            Object val = args[i];
            for (Annotation annotation : annotations) {
                if (annotation instanceof CNotBlank) {
                    if (StringUtils.isBlank((String) val)) {
                        throw new CustomException(StrUtil.format("参数 {} 不可为空", parameters[i].getName()));
                    }
                }
                if (annotation instanceof CNotNull) {
                    if (val == null) {
                        throw new CustomException(StrUtil.format("参数 {} 不可为NULL", parameters[i].getName()));
                    }
                }
            }
        }
    }
}
